<?php

namespace App\Console\Commands;

use App\UserChange;
use App\UserCoin;
use Carbon\Carbon;
use Illuminate\Console\Command;

class WechatLuckyMoney extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'wechat:luckyMoney';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $wechat = app('wechat');
        $luckyMoney = $wechat->lucky_money;

        $changes = UserChange::where('status', 0)->where('created_at', '<', Carbon::now()->subMinutes(5))->get();
        foreach ($changes as $change) {
            $data = $luckyMoney->query($change->trade_id);

            if ($data->return_code == 'SUCCESS' && $data->result_code == 'SUCCESS') {
                if (in_array($data->status, array('FAILED', 'SENDING'))) {
                    $change->status = 2;
                    $change->save();
                }
                if (in_array($data->status, array('SENT', 'RECEIVED', 'RFUND_ING', 'REFUND'))) {
                    $change->status = 1;
                    $change->save();
                }
            } else {
                $change->status = 2;
                $change->save();
            }

            if ($change->status == 2) {
                $change->status = 3;
                $change->save();

                $key = '0-' . $change->user_id . '-' . $change->amount . '-' . $change->id . '-12';
                UserCoin::log(0, $change->user_id, UserCoin::TYPE_ZS, $change->amount, '提现失败返还', $key, 'in');
            }
        }
    }
}
